package vn.bang.utility;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public final class ImageUtil {

	static public Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
        int original_width = imgSize.width;
        int original_height = imgSize.height;
        int bound_width = boundary.width;
        int bound_height = boundary.height;
        int new_width = original_width;
        int new_height = original_height;

        // first check if we need to scale width
        if (original_width > bound_width) {
            //scale width to fit
            new_width = bound_width;
            //scale height to maintain aspect ratio
            new_height = (new_width * original_height) / original_width;
        }

        // then check if we need to scale even with the new height
        if (new_height > bound_height) {
            //scale height to fit instead
            new_height = bound_height;
            //scale width to maintain aspect ratio
            new_width = (new_height * original_width) / original_height;
        }

        return new Dimension(new_width, new_height);
    }
	
	static public Image fit(BufferedImage imageBuff, Dimension toFit, ImageObserver observer) {
    	double scaleFactor = Math.min(1d, getScaleFactorToFit(new Dimension(imageBuff.getWidth(), imageBuff.getHeight()), toFit));

        int scaleWidth = (int) Math.round(imageBuff.getWidth() * scaleFactor);
        int scaleHeight = (int) Math.round(imageBuff.getHeight() * scaleFactor);

        Image scaled = imageBuff.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);

        int width = (int)toFit.getWidth() - 1;
        int height = (int)toFit.getHeight() - 1;

        int x = (width - scaled.getWidth(observer)) / 2;
        int y = (height - scaled.getHeight(observer)) / 2;
        
        return scaled;
	}
	
	static public double getScaleFactor(int iMasterSize, int iTargetSize) {

        double dScale = 1;
        if (iMasterSize > iTargetSize) {

            dScale = (double) iTargetSize / (double) iMasterSize;

        } else {

            dScale = (double) iTargetSize / (double) iMasterSize;

        }

        return dScale;

    }

    static public double getScaleFactorToFit(Dimension original, Dimension toFit) {

        double dScale = 1d;

        if (original != null && toFit != null) {

            double dScaleWidth = getScaleFactor(original.width, toFit.width);
            double dScaleHeight = getScaleFactor(original.height, toFit.height);

            dScale = Math.min(dScaleHeight, dScaleWidth);

        }

        return dScale;

    }
	
	/**
	 * Prevent constructor.
	 */
	private ImageUtil() {
	}

}
